package acs.http;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.controller.MessageObserver;

import java.util.HashMap;
import java.util.Map;

public class HttpController  implements MessageObserver {
    private static HttpController instance=new HttpController();
    private HttpController(){}
	private Map<String,DmsService> serviceMap=new HashMap<>();
    public static HttpController getInstance(){
        return instance;
    }

    @Override
    public void handle(int eventType, Params param) {
        switch (eventType) {
            case EventType.CLICK_REQUEST:
            	this.getOrGeneratorDmsService(param).handleRequest(param);
                break;
            case EventType.RESPONSE_FOR_DATA:
            	this.getOrGeneratorDmsService(param).sendResponse(param);
                break;
            case EventType.TIMEOUT_FOR_CACHE_OFFER:
            	this.getOrGeneratorDmsService(param).clearCache(param);
            	break;
            case EventType.TIMEOUT_FOR_DMS_SERVICE:
            	serviceMap.remove(param.get(Constant.REQUEST_TYPE).toString());
            	break;
            case EventType.TIMEOUT_FOR_LOAD_DATA:
            	this.getOrGeneratorDmsService(param).doNotResponseDataToClient(param);
            	break;
            case EventType.REMOVE_TASK:
            	this.getOrGeneratorDmsService(param).removeTask(param);
            	break;
        }
    }

	/**
	 * 得到之前生成的DmsService
	 * @param params
	 * @return
	 */
	private DmsService getPreDmsService(Params params) {
		String requestType = params.get(Constant.REQUEST_TYPE);
		if(requestType == null) {
			System.out.println("");//这里只是为了调错
		}
		DmsService dmsService = serviceMap.get(requestType);
		if(dmsService == null) {
			throw new RuntimeException("程序出错，没有获取到前面保存的DmsService");
		}
		return dmsService;
	}
	/**
	 * 获取或创建DmsService，在刚开始处理请求时，调用此方法
	 * @param params
	 * @return
	 */
	private DmsService getOrGeneratorDmsService(Params params) {
		String requestType = params.get(Constant.REQUEST_TYPE);
		DmsService dmsService = serviceMap.get(requestType);
		if(dmsService == null) {
			dmsService=new DmsService(this);
			serviceMap.put(requestType, dmsService);
			DMSSoftTimer.getInstance().startTimer(Constant.MAX_WAIT_TASK_TIME, EventType.TIMEOUT_FOR_DMS_SERVICE,params);
		}
		return dmsService;
	}
	@Override
	public void removeService(String requestType) {
		serviceMap.remove(requestType);
	}
   
}
